package com.example.datagramsocket

import android.widget.Toast
import com.binyouwei.udp_lib.factory.UnicastFactory
import com.example.datagramsocket.base.BaseActivity
import com.example.datagramsocket.databinding.ActivityUnicasBinding
import com.example.datagramsocket.utils.MMKVCache

/**
 * 单播
 */
class UnicastActivity : BaseActivity<ActivityUnicasBinding>() {
    val mFactory: UnicastFactory by lazy { UnicastFactory() }
    val unicastTargetIp = "unicastTargetIp"

    override fun initView() {
        mBinding.apply {
            mFactory.initUdp()

            targetIp.setText(MMKVCache.getString(unicastTargetIp))
            sureBtn.setOnClickListener {
                val ip = targetIp.text.toString()
                if (ip.isEmpty()) {
                    Toast.makeText(this@UnicastActivity, "请输入目标ip", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                mFactory.onReceiveMessageListener(ip) { msg ->
                    this@UnicastActivity.runOnUiThread {
                        receiveMessage.text = msg
                    }
                }
            }
            sendBtn.setOnClickListener {
                if (targetIp.text.toString().isEmpty()) {
                    Toast.makeText(this@UnicastActivity, "请输入目标ip", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                } else if (sendMessage.text.toString().isEmpty()) {
                    Toast.makeText(this@UnicastActivity, "消息不能为空", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }

                targetIp.text.toString().let { value ->
                    MMKVCache.putString(unicastTargetIp, value)
                    mFactory.sendMessage(targetIp.text.toString(), sendMessage.text.toString())
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mFactory.destroyUdp()
    }

}